<script setup lang="ts">
import moment from "moment";
import { onMounted, ref, watchEffect } from "vue";
import {
  Exam,
  ExamControllerService,
  ExamQueryRequest,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

const router = useRouter();

// Question 部分
const tableRefQuestion = ref();
const dataListQuestion = ref([]);
const totalQuestion = ref(0);
const searchParamsQuestion = ref<QuestionQueryRequest>({
  pageSize: 8,
  current: 1,
});

const loadDataQuestion = async () => {
  const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
    searchParamsQuestion.value
  );
  if (res.code === 0) {
    dataListQuestion.value = res.data.records;
    totalQuestion.value = res.data.total;
  } else {
    message.error("加载失败" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadDataQuestion();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadDataQuestion();
});

const columnsQuestion = [
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "题目名称",
    dataIndex: "title",
  },
  {
    title: "标签",
    slotName: "tags",
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    slotName: "optional",
  },
];

const onPageChangeQuestion = (page: number) => {
  searchParamsQuestion.value = {
    ...searchParamsQuestion.value,
    current: page,
  };
};

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

// Exam 部分
const tableRefExam = ref();
const dataListExam = ref([]);
const totalExam = ref(0);
const searchParamsExam = ref<ExamQueryRequest>({
  pageSize: 8,
  current: 1,
});

const loadDataExam = async () => {
  const res = await ExamControllerService.listExamVoByPageUsingPost(
    searchParamsExam.value
  );
  if (res.code === 0) {
    dataListExam.value = res.data.records;
    totalExam.value = res.data.total;
  } else {
    message.error("加载失败" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadDataExam();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadDataExam();
});

const columnsExam = [
  {
    title: "考场号",
    dataIndex: "id",
  },
  {
    title: "考场名",
    dataIndex: "examName",
  },
  {
    title: "描述",
    dataIndex: "examDesc",
  },
  {
    title: "创建者",
    dataIndex: "userId",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    title: "开始时间",
    slotName: "startTime",
  },
  {
    slotName: "optional",
  },
];

const onPageChangeExam = (page: number) => {
  searchParamsExam.value = {
    ...searchParamsExam.value,
    current: page,
  };
};

/**
 * 跳转到考试页面
 * @param exam
 */
const toExamQuestion = (exam: Exam) => {
  router.push({
    path: "/view/examination",
    query: { id: exam.id },
  });
};

const isExamAvailable = (startTime: string) => {
  if (!startTime) return false;
  return new Date().getTime() >= new Date(startTime).getTime();
};
</script>

<template>
  <div class="home">
    <div class="title">分布式OJ在线评测系统</div>
  </div>
  <br />
  <br />
  <div class="title">题目</div>
  <div class="questionView">
    <a-table
      :ref="tableRefQuestion"
      :columns="columnsQuestion"
      :data="dataListQuestion"
      :pagination="{
        showTotal: true,
        pageSize: searchParamsQuestion.pageSize,
        current: searchParamsQuestion.current,
        totalQuestion,
      }"
      @page-change="onPageChangeQuestion"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tags" :key="index" color="green"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #acceptedRate="{ record }">
        {{
          record.submitNum
            ? `${((record.acceptedNum / record.submitNum) * 100).toFixed(
                2
              )}% (${record.acceptedNum}/${record.submitNum})`
            : "0% (0/0)"
        }}
      </template>

      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="toQuestionPage(record)">
            做题
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
  <br />
  <br />
  <div class="title">考试</div>
  <div class="examinationView">
    <a-table
      :ref="tableRefExam"
      :columns="columnsExam"
      :data="dataListExam"
      :pagination="{
        showTotal: true,
        pageSize: searchParamsExam.pageSize,
        current: searchParamsExam.current,
        totalExam,
      }"
      @page-change="onPageChangeExam"
    >
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #startTime="{ record }">
        {{ moment(record.startTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button
            type="primary"
            @click="toExamQuestion(record)"
            :disabled="!isExamAvailable(record.startTime)"
          >
            进入考试
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<style scoped>
#examinationView {
  max-width: 1280px;
  margin: 0 auto;
}
#questionsView {
  max-width: 1280px;
  margin: 0 auto;
}
.title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  padding: 16px 0;
  border-bottom: 2px solid #ddd;
}
</style>
